﻿using AutoMapper;
using DeZhen.CollaborationPlatform.IRepository.ApiManagement;
using DeZhen.CollaborationPlatform.IService.ApiManagement;
using DeZhen.CollaborationPlatform.Model.Common;
using DeZhen.CollaborationPlatform.Model.DTO.ApiManagement;
using DeZhen.CollaborationPlatform.Model.Entities;
using SqlSugar;
using Yitter.IdGenerator;

namespace DeZhen.CollaborationPlatform.Service.ApiManagement
{
    /// <summary>
    /// 接口管理服务实现
    /// </summary>
    public class ApiManagementService : IApiManagementService
    {
        private readonly IApiManagementRepository _repository;
        private readonly IMapper _mapper;

        public ApiManagementService(IApiManagementRepository repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取接口管理分页列表
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <returns></returns>
        public async Task<PageResult<ApiManagementDTO>> GetListToPageAsync(QueryApiManagementPage param)
        {
            var items = (await _repository.GetListAsync())
                         .WhereIF(!string.IsNullOrEmpty(param.ApiName), x => x.ApiName.Contains(param.ApiName))
                         .WhereIF(!string.IsNullOrEmpty(param.ApiGroup), x => x.ApiGroup.Contains(param.ApiGroup))
                         .WhereIF(!string.IsNullOrEmpty(param.ApiOwner), x => x.ApiOwner.Contains(param.ApiOwner))
                         .WhereIF(param.Status.HasValue, x => x.Status == param.Status.Value)
                         .OrderByDescending(x => x.CreateTime)
                         .Skip((param.Page - 1) * param.PageSize)
                         .Take(param.PageSize)
                         .ToList();

            var result = _mapper.Map<List<ApiManagementDTO>>(items);

            var totalCount = (await _repository.GetListAsync())
                             .WhereIF(!string.IsNullOrEmpty(param.ApiName), x => x.ApiName.Contains(param.ApiName))
                             .WhereIF(!string.IsNullOrEmpty(param.ApiGroup), x => x.ApiGroup.Contains(param.ApiGroup))
                             .WhereIF(!string.IsNullOrEmpty(param.ApiOwner), x => x.ApiOwner.Contains(param.ApiOwner))
                             .WhereIF(param.Status.HasValue, x => x.Status == param.Status.Value)
                             .Count();

            return new PageResult<ApiManagementDTO>
            {
                TotalCount = totalCount,
                Items = result
            };
        }

        /// <summary>
        /// 获取接口管理列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<List<ApiManagementDTO>> GetListAsync(QueryApiManagement param)
        {
            var items = (await _repository.GetListAsync())
                         .WhereIF(!string.IsNullOrEmpty(param.ApiName), x => x.ApiName.Contains(param.ApiName))
                         .WhereIF(!string.IsNullOrEmpty(param.ApiGroup), x => x.ApiGroup.Contains(param.ApiGroup))
                         .WhereIF(!string.IsNullOrEmpty(param.ApiOwner), x => x.ApiOwner.Contains(param.ApiOwner))
                         .WhereIF(param.Status.HasValue, x => x.Status == param.Status.Value)
                         .OrderByDescending(x => x.CreateTime)
                         .ToList();

            return _mapper.Map<List<ApiManagementDTO>>(items);
        }

        /// <summary>
        /// 根据ID获取接口管理对象
        /// </summary>
        /// <param name="id">接口ID</param>
        /// <returns></returns>
        public async Task<ApiManagementDTO> GetByIdAsync(long id)
        {
            var model = await _repository.GetByIdAsync(id);
            return _mapper.Map<ApiManagementDTO>(model);
        }

        /// <summary>
        /// 添加接口管理
        /// </summary>
        /// <param name="input">输入参数</param>
        /// <returns></returns>
        public async Task<long> AddAsync(ApiManagementAdd input)
        {
            var queryResult = (await _repository.GetListAsync())
                                .WhereIF(!string.IsNullOrEmpty(input.ApiName), x => x.ApiName.Equals(input.ApiName));

            // 检查接口名称是否已存在
            if (queryResult.Any())
            {
                throw new Exception("接口名称已存在");
            }

            var model = _mapper.Map<ApiManagementAdd, ApiManagements>(input);
            model.Id = YitIdHelper.NextId();
            model.CreateTime = DateTime.Now;

            await _repository.CreateAsync(model);

            return model.Id;
        }

        /// <summary>
        /// 更新接口管理
        /// </summary>
        /// <param name="input">输入参数</param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(ApiManagementEdit input)
        {
            var model = await _repository.GetByIdAsync(input.Id);
            if (model == null)
            {
                throw new Exception("接口管理信息为空");
            }

            var result = _mapper.Map(input, model);
            result.UpdateTime = DateTime.Now;

            return await _repository.UpdateAsync(result);
        }

        /// <summary>
        /// 删除接口管理
        /// </summary>
        /// <param name="id">接口ID</param>
        /// <returns></returns>
        public async Task DeleteAsync(long id)
        {
            var model = await _repository.GetByIdAsync(id);
            if (model == null)
            {
                throw new Exception("接口管理信息为空");
            }

            await _repository.DeleteAsync(id);
        }
    }
}